package leetcode.code0857;

import java.util.Arrays;
import java.util.PriorityQueue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public double mincostToHireWorkers(int[] quality, int[] wage, int k) {
		// total * quality[i] / quality_sum_[1..k] >= wage[i]
		// sum * w / q
		int len = quality.length;
		Integer[] sort = new Integer[len];
		for (int i = 0; i < sort.length; i++) {
			sort[i] = i;
		}
		Arrays.sort(sort, (a, b) -> quality[b] - quality[a]);
		// int[]{wage,quality}
//		PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> b[0] / b[1] - a[0] / a[1]);
		PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> b[0] * a[1] - a[0] * b[1]);
		int sum = 0, p = 0;
		double ans = 0d;
		while (p < k) {
			sum += quality[sort[p]];
			queue.add(new int[] { wage[sort[p]], quality[sort[p]] });
			p++;
		}
		while (p < len) {
			int w = wage[sort[p]], q = quality[sort[p]];
			int[] top = queue.peek();
			double val1 = 1d * sum * top[0] / top[1];
			double val2 = 1d * (sum - top[1] + q) * w / q;
			if (val2 < val1) {
				queue.poll();
				queue.add(new int[] { w, q });
				sum += q - top[1];

			}
			ans = Math.min(val1, val2);
			p++;
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(105d, this.mincostToHireWorkers(H.str2array3("[10,20,5]"), H.str2array3("[70,50,30]"), 2));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
